package com.mission.game.playgame;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.mission.game.R;
import com.mission.game.components.PlayGPSHelper;
import com.mission.game.components.Statusable.Status;
import com.mission.game.utils.GPSTask;
import com.mission.game.utils.Task;

public class PlayGPSTask extends PlayAbstractTask {

	private static final int OPEN_MAP = 8;
	private static boolean _isNear;

	@Override
	protected int getContentView() {
		return R.layout.play_gps_task;
	}

	@Override
	protected int getNameInput() {
		return R.id.play_gps_name;
	}

	@Override
	protected int getDescriptionInput() {
		return R.id.play_gps_description;
	}

	@Override
	protected void setSpecificFields() {
		_isNear = false;
	}

	public void onOpenMapClicked(View v) {
		Intent i = new Intent(getApplicationContext(), PlayGPSHelper.class);
		i.putExtra("latitude", ((GPSTask) _task).getLatitude()).putExtra(
				"longitude", ((GPSTask) _task).getLongitude());
		startActivityForResult(i, OPEN_MAP);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == OPEN_MAP && resultCode == RESULT_OK && data != null
				&& data.getExtras() != null) {
			Bundle extras = data.getExtras();
			int lat = 0;
			int lon = 0;
			if (extras.containsKey("latitude")) {
				lat = extras.getInt("latitude");
			}
			if (extras.containsKey("longitude")) {
				lon = extras.getInt("longitude");
			}
			float[] results = new float[1];
			Location.distanceBetween(lat / 1E6, lon / 1E6,
					((GPSTask) _task).getLatitude() / 1E6,
					((GPSTask) _task).getLongitude() / 1E6, results);
			Toast.makeText(getApplicationContext(),
					"You are " + results[0] + " meters away from target.",
					Toast.LENGTH_LONG).show();
			if (results[0] < 5) {
				_isNear = true;
			}
		}
	}

	@Override
	public void onBackToMissionClicked(View v) {
		if (_isNear) {
			_task.setStatus(Status.COMPLETED);
		} else {
			_task.setStatus(Status.REJECTED);
		}
		_task.setStatus(Task.Status.COMPLETED); // DEMO MODE! TODO: remove for production 
		getIntent().putExtra("task", _task);
		setResult(RESULT_OK, getIntent());
		finish();
	}

}
